package com.pointstar.dp.modules.project.util;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 * @author 朱科睿
 * @since 2022/12/14 17:49
 */
public class LocalDateUtil {

    public static void main(String[] args) {

        // 获取当前时间
        LocalDate localDate = LocalDate.now();
        LocalTime localTime = LocalTime.now();
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(localDate);
        System.out.println(localTime);
        System.out.println(localDateTime);

        // 根据指定日期/时间创建对象
        LocalDate localDate1 = LocalDate.of(2018, 1, 13);
        LocalTime localTime1 = LocalTime.of(9, 43, 20);
        LocalDateTime localDateTime1 = LocalDateTime.of(2018, 1, 13, 9, 43, 20);
        System.out.println(localDate1);
        System.out.println(localTime1);
        System.out.println(localDateTime1);

        // 旧API转新API
        // Date -> Instant:
        Instant ins1 = new Date().toInstant();

        // Calendar -> Instant -> ZonedDateTime:
        Calendar calendar = Calendar.getInstance();
        Instant ins2 = calendar.toInstant();
        ZonedDateTime zdt = ins2.atZone(calendar.getTimeZone().toZoneId());

        // 新API转旧API
        // ZonedDateTime -> long:
        ZonedDateTime zdt1 = ZonedDateTime.now();
        long ts = zdt1.toEpochSecond() * 1000;

        // long -> Date:
        Date date = new Date(ts);

        // long -> Calendar:
        Calendar calendar1 = Calendar.getInstance();
        calendar1.clear();
        calendar1.setTimeZone(TimeZone.getTimeZone(zdt1.getZone().getId()));
        calendar1.setTimeInMillis(zdt1.toEpochSecond() * 1000);

        LocalDate d = LocalDate.now(); // 当前日期
        LocalTime t = LocalTime.now(); // 当前时间
        LocalDateTime dt = LocalDateTime.now(); // 当前日期和时间
        System.out.println(d); // 严格按照ISO 8601格式打印
        System.out.println(t); // 严格按照ISO 8601格式打印
        System.out.println(dt); // 严格按照ISO 8601格式打印

        // 自定义格式化:
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        System.out.println(dtf.format(LocalDateTime.now()));

    }

}
